package com.petShop.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {

    public LoginFilter() {
    }


	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();

		String loginURL = req.getContextPath()+"/login";
		String adminURL = req.getContextPath()+"/admin";
		boolean loginRequest = req.getRequestURI().equals(loginURL);
		boolean adminRequest = req.getRequestURI().equals(adminURL);
		boolean resourceRequest = req.getRequestURI().startsWith(req.getContextPath()+"/resources"+"/");
		boolean userloggedIn = (session != null) 
				&& (session.getAttribute("username") != null);

		boolean adminloggedIn = (session != null) 
				&&(session.getAttribute("aUsername") != null);
		String returnUrl = req.getRequestURI();
		//System.out.println("filter "+returnUrl);
		boolean reqAdminUrl = false;
		if(returnUrl!=null){
			if(returnUrl.length()>6&&returnUrl.substring(0,6).equals("/admin")){
				reqAdminUrl = true; 
			}else if(returnUrl.equals("/admin")){
				session.removeAttribute("returnUrl");
				//session.invalidate();
				//System.out.println("returnUrl session clear");
			}
		}
		//System.out.println("adminRequest"+adminRequest);
		//System.out.println(reqAdminUrl);		
		if((userloggedIn&&!reqAdminUrl) ||
				(adminloggedIn&&reqAdminUrl)|| 
				loginRequest || resourceRequest||adminRequest){
			if(!resourceRequest){
				res.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");//no-cache时，浏览器就不会缓存
				res.setHeader("Pragma","no-cache");
				res.setDateHeader("Expires", 0);
			}
			
		}else{
			if(returnUrl!=null){
				if((reqAdminUrl)){
					session.setAttribute("AdminReturnUrl", returnUrl);
					res.sendRedirect(adminURL);
				}else if(returnUrl.equals("/buy")){
					session.setAttribute("returnUrl", returnUrl);
					res.sendRedirect(loginURL);
				}else if(returnUrl.length()>=9&&returnUrl.substring(0,9).equals("/userinfo")){
					session.setAttribute("returnUrl", returnUrl);
					res.sendRedirect(loginURL);
				}else{
					res.sendRedirect(loginURL);
				}
				return;
			}
		}
		chain.doFilter(req, res);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		
	}

}
